package io.itit.ecp.admin.server.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import icu.mhb.mybatisplus.plugln.base.service.impl.JoinServiceImpl;
import io.itit.ecp.admin.server.entity.EarlyWarningEntity;
import io.itit.ecp.admin.server.entity.EarlyWarningThresholdEntity;
import io.itit.ecp.admin.server.entity.EarlyWarningUserEntity;
import io.itit.ecp.admin.server.mapper.EarlyWarningMapper;
import io.itit.ecp.admin.server.service.IEarlyWarningService;
import io.itit.ecp.admin.server.service.IEarlyWarningThresholdService;
import io.itit.ecp.admin.server.service.IEarlyWarningUserService;
import io.itit.grass.common.exception.GrassException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *
 * @Author：Roy
 * @Description：预警服务实现类
 * @Date：Create by 2023-12-04 15:28:53
 */
@Service
public class EarlyWarningServiceImpl extends JoinServiceImpl<EarlyWarningMapper, EarlyWarningEntity> implements IEarlyWarningService {

    @Resource
    private IEarlyWarningThresholdService earlyWarningThresholdService;

    @Resource
    private IEarlyWarningUserService earlyWarningUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean saveEarlyWarning(EarlyWarningEntity earlyWarning, List<String> userIds, String thresholdJson) {
        boolean res = this.save(earlyWarning);
        return res && this.savePushUserAndThreshold(earlyWarning.getId(), userIds, thresholdJson);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateEarlyWarning(EarlyWarningEntity earlyWarning, List<String> userIds, String thresholdJson) {
        boolean res = this.updateById(earlyWarning);
        this.deletePushUserAndThreshold(earlyWarning.getId());
        return res && this.savePushUserAndThreshold(earlyWarning.getId(), userIds, thresholdJson);
    }

    @Override
    public List<EarlyWarningThresholdEntity> getEarlyWarningThreshold(String earlyWarningId){
        return earlyWarningThresholdService.lambdaQuery()
                .eq(EarlyWarningThresholdEntity::getEarlyWarningId, earlyWarningId)
                .list();
    }

    @Override
    public List<EarlyWarningUserEntity> getEarlyWarningUser(String earlyWarningId){
        return earlyWarningUserService.lambdaQuery()
                .eq(EarlyWarningUserEntity::getEarlyWarningId, earlyWarningId)
                .list();
    }

    /**
     * 保存推送用户和预警规则
     * @param earlyWarningId 预警设置ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public boolean savePushUserAndThreshold(String earlyWarningId, List<String> userIds, String thresholdJson){
        GrassException.throwEx(!JSON.isValidArray(thresholdJson), "预警阀值不能为空");
        List<EarlyWarningThresholdEntity> thresholds = JSONArray.parseArray(thresholdJson, EarlyWarningThresholdEntity.class);
        thresholds.forEach(threshold-> threshold.setEarlyWarningId(earlyWarningId));
        boolean res = earlyWarningThresholdService.saveBatch(thresholds);

        GrassException.throwEx(userIds==null || userIds.size() <= 0, "推送目标不能为空");
        List<EarlyWarningUserEntity> warningUsers = userIds.stream().map(userId->{
            EarlyWarningUserEntity warningUser = new EarlyWarningUserEntity();
            warningUser.setUserId(userId);
            warningUser.setEarlyWarningId(earlyWarningId);
            return warningUser;
        }).collect(Collectors.toList());
        return res && earlyWarningUserService.saveBatch(warningUsers);
    }

    /**
     * 删除之前的推送用户和预警规则
     * @param earlyWarningId 预警设置ID
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    public void deletePushUserAndThreshold(String earlyWarningId){
        if (earlyWarningId == null){
            return;
        }
        earlyWarningThresholdService.lambdaUpdate().eq(EarlyWarningThresholdEntity::getEarlyWarningId, earlyWarningId).remove();
        earlyWarningUserService.lambdaUpdate().eq(EarlyWarningUserEntity::getEarlyWarningId, earlyWarningId).remove();
    }
}
